{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %}
{% import "bootstrap/fixes.html" as fixes %}
{% import "bootstrap/utils.html" as util %}

{% block title %}{{ compath.stylize_plugin_name(STYLED_NAMES, resource) }} Pathway Database Distributions{% endblock %}

{% block styles %}
    {{ super() }}

    <style>

        /* Histogram CSS */

        .bar rect {
            fill: steelblue;
        }

        .bar text {
            fill: #fff;
            font: 10px sans-serif;
        }

        .bar:hover {
            fill: brown;
        }

        .toolTip {
            position: absolute;
            display: none;
            min-width: 80px;
            height: auto;
            background: none repeat scroll 0 0 #ffffff;
            border: 1px solid #6F257F;
            padding: 14px;
            text-align: center;
        }
    </style>
{% endblock %}

{% block scripts %}
    {{ super() }}
    {% include "dependencies/common.html" %}
    {% include "dependencies/datatables.html" %}

    <script type="text/javascript"
            src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>


    <script>

        var databaseName = '{{ resource|safe }}';
        // If a new database is added the number of bins needs to be here (otherwise you would be by default 40)
        var databaseNumberOfBins = {
            'kegg': 40,
            'reactome': 25,
            'wikipathways': 40,
            'compath_neurommsig_ad': 10,
            'compath_neurommsig_pd': 10
        };

        var numberOfBins;
        if (databaseName in databaseNumberOfBins) {
            numberOfBins = databaseNumberOfBins[databaseName]
        }
        else {
            numberOfBins = 40;
        }

        $(document).ready(function () {

            $("#info-table").DataTable(
                {
                    dom: "<'row'<'col-sm-2'l><'col-sm-3'f><'col-sm-5'B>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-5'i><'col-sm-7'p>>",
                    buttons: [
                        'copy', 'csv', 'excel', 'pdf', 'print'
                    ]
                }
            );

            var data = {{ pathway_data|safe }};

            /* Plot Histogram */

            var histogramData = [];
            $.each(data, function (key, value) {
                histogramData.push(value[1]);
            });

            var formatCount = d3.format(",.0f");

            var margin = {
                    top: 10,
                    right: 30,
                    bottom: 50,
                    left: 30
                },
                width = $('.panel-body').width() - (margin.right + margin.left),
                height = 300;

            var svg = d3.select("#histogram-pathways").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                    "translate(" + margin.left + "," + margin.top + ")");


            var tooltip = d3.select("body").append("div").attr("class", "toolTip");

            var x = d3.scaleLinear()
                .domain(d3.extent(histogramData))
                .rangeRound([0, width]);

            var histogram = d3.histogram()
                .domain(x.domain())
                .thresholds(x.ticks(numberOfBins));

            var bins = histogram(histogramData);

            var y = d3.scaleLinear()
                .domain([0, d3.max(bins, function (d) {
                    return d.length;
                })])
                .range([height, 0]);

            var bar = svg.selectAll(".bar")
                .data(bins)
                .enter().append("g")
                .attr("class", "bar")
                .attr("transform", function (d) {
                    return "translate(" + x(d.x0) + "," + y(d.length) + ")";
                })
                .on("mousemove", function (d) {
                    tooltip
                        .style("left", d3.event.pageX - 50 + "px")
                        .style("top", d3.event.pageY - 70 + "px")
                        .style("display", "inline-block")
                        .html((d.length) + "<br>" + "Pathways");
                })
                .on("mouseout", function (d) {
                    tooltip.style("display", "none");
                });

            bar.append("rect")
                .attr("x", 1)
                .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
                .attr("height", function (d) {
                    return height - y(d.length);
                });

            bar.append("text")
                .attr("dy", ".75em")
                .attr("y", 6)
                .attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
                .attr("text-anchor", "middle")
                .text(function (d) {
                    return formatCount(d.length);
                });

            svg.append("g")
                .attr("class", "axis axis--x")
                .attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(x));

            // text label for the x axis
            svg.append("text")
                .attr("transform",
                    "translate(" + (width / 2) + " ," +
                    (height + margin.top + 20) + ")")
                .style("text-anchor", "middle")
                .text("Size of the Gene Set");

            // text label for the y axis
            svg.append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 0 - margin.left)
                .attr("x", 0 - (height / 2))
                .attr("dy", "1em")
                .style("text-anchor", "middle")
                .text("Number of Pathways with a similar Size");


        });
    </script>

    <script>

        var databaseName = '{{ resource|safe }}';
        // If a new database is added the number of bins needs to be here (otherwise you would be by default 40)
        var databaseNumberOfBins = {
            'kegg': 30,
            'reactome': 25,
            'wikipathways': 25,
            'compath_neurommsig_ad': 10,
            'compath_neurommsig_pd': 10
        };

        var numberOfBins;
        if (databaseName in databaseNumberOfBins) {
            numberOfBins = databaseNumberOfBins[databaseName]
        }
        else {
            numberOfBins = 40;
        }

        $(document).ready(function () {

            $("#overview-table").DataTable(
                {
                    dom: "<'row'<'col-sm-2'l><'col-sm-3'f><'col-sm-5'B>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-5'i><'col-sm-7'p>>",
                    buttons: [
                        'copy', 'csv', 'excel', 'pdf', 'print'
                    ]
                }
            );

            var data = {{ gene_data|safe }};

            /* Plot Histogram */

            var histogramData = [];
            $.each(data, function (key, value) {
                histogramData.push(value)
            });

            var formatCount = d3.format(",.0f");

            var margin = {
                    top: 10,
                    right: 30,
                    bottom: 50,
                    left: 30
                },
                width = $('.panel-body').width() - (margin.right + margin.left),
                height = 300;

            var svg = d3.select("#histogram-genes").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                    "translate(" + margin.left + "," + margin.top + ")");

            var tooltip = d3.select("body").append("div").attr("class", "toolTip");

            var x = d3.scaleLinear()
                .domain([0, 50])
                .rangeRound([0, width]);

            var histogram = d3.histogram()
                .domain(x.domain())
                .thresholds(x.ticks(numberOfBins));

            var bins = histogram(histogramData);

            var y = d3.scaleLinear()
                .domain([0, d3.max(bins, function (d) {
                    return d.length;
                })])
                .range([height, 0]);

            var bar = svg.selectAll(".bar")
                .data(bins)
                .enter().append("g")
                .attr("class", "bar")
                .attr("transform", function (d) {
                    return "translate(" + x(d.x0) + "," + y(d.length) + ")";
                })
                .on("mousemove", function (d) {
                    tooltip
                        .style("left", d3.event.pageX - 50 + "px")
                        .style("top", d3.event.pageY - 70 + "px")
                        .style("display", "inline-block")
                        .html((d.length) + "<br>" + "Genes");
                })
                .on("mouseout", function (d) {
                    tooltip.style("display", "none");
                });

            bar.append("rect")
                .attr("x", 1)
                .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
                .attr("height", function (d) {
                    return height - y(d.length);
                });

            bar.append("text")
                .attr("dy", ".75em")
                .attr("y", 6)
                .attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
                .attr("text-anchor", "middle")
                .text(function (d) {
                    return formatCount(d.length);
                });

            svg.append("g")
                .attr("class", "axis axis--x")
                .attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(x));


            // text label for the x axis
            svg.append("text")
                .attr("transform",
                    "translate(" + (width / 2) + " ," +
                    (height + margin.top + 20) + ")")
                .style("text-anchor", "middle")
                .text("Total number of Pathways associated with a gene");

            // text label for the y axis
            svg.append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 0 - margin.left)
                .attr("x", 0 - (height / 2))
                .attr("dy", "1em")
                .style("text-anchor", "middle")
                .text("Number of Genes");

        });
    </script>

{% endblock %}

{% import "meta/macros.html" as compath %}


{% block content %}
    <div class="container" style="margin-top: 50px">
        {{ util.flashed_messages(dismissible=True, container=False) }}

        <div class="page-header">
            <h1>{{ compath.stylize_plugin_name(STYLED_NAMES, resource) }} Distribution Summary</h1>
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">Pathway Size Distribution</div>
            <div class="panel-body">
                <p>Explore the distribution of the pathway sizes across different resources. The aim of this plot is
                    just to show the distribution and the outliers, in order to inspect and find the name of the
                    outliers, please use the table in the section below.
                </p>

                <div id="histogram-pathways"></div>

                <p>Explore the histogram in detail using the table below.</p>

                <table id="info-table" class="table table-striped table-hover">
                    <thead>
                    <tr>
                        <th class="first-row">Pathway Name</th>
                        <th class="first-row">Gene Set Size</th>
                    </tr>
                    </thead>
                    <tbody>

                    {% for identifier, (name, size) in pathway_data.items() %}

                        <tr>
                            <td>
                                {% if resource == "reactome" %}
                                    <a href="https://reactome.org/PathwayBrowser/#/{{ identifier }}">
                                        {{ name }}
                                    </a>
                                {% elif resource == "kegg" %}
                                    <a href="http://www.kegg.jp/kegg-bin/show_pathway?map=map{{ identifier|remove_prefix('path:hsa') }}&show_description=show">
                                        {{ name }}
                                    </a>
                                {% elif resource == "wikipathways" %}
                                    <a href="https://www.wikipathways.org/index.php/Pathway:{{ identifier }}">
                                        {{ name }}
                                    </a>
                                {% elif resource == "msig" %}
                                    <a href="http://www.broadinstitute.org/gsea/msigdb/cards/{{ identifier }}">
                                        {{ name }}
                                    </a>
                                {% else %}
                                    {{ name }}
                                {% endif %}
                            </td>
                            <td>{{ size }}</td>
                        </tr>

                    {% endfor %}

                    </tbody>

                </table>
            </div>
        </div>
        <hr>
        <div class="panel panel-default">
            <div class="panel-heading">Gene Distribution over Pathways</div>
            <div class="panel-body">
                <p>Explore the distribution of the all the genes in databases across pathways. The aim of this plot
                    is just to show the more promiscuous genes in pathway databases, in order to inspect and find the
                    name of the outliers, please use the table in the section below. Based on the distributions
                    of KEGG, Reactome, and WikiPathways, we decided to show only the distribution of genes functionally
                    annotated from zero to fifty pathways (x axis ranges from [0,50]). The reason for this is that
                    there are a few genes acting in 100 pathways or more and disrupt that distort the plot.
                    In order to pinpoint the most promiscuous genes, please use the sorting functionality of the table
                    below.
                </p>

                <div id="histogram-genes"></div>

                <p>Explore the histogram in detail using the table below.</p>

                <table id="overview-table" class="table table-striped table-hover">
                    <thead>
                    <tr>
                        <th class="first-row">Gene Symbol</th>
                        <th class="first-row">Number of Pathways</th>
                    </tr>
                    </thead>
                    <tbody>

                    {% for gene, pathways_associated in gene_data.items() %}

                        <tr>
                            <td>
                                <a href="https://www.ncbi.nlm.nih.gov/gene/?term={{ gene }}">{{ gene }}</a>
                            </td>
                            <td>{{ pathways_associated }}</td>
                        </tr>

                    {% endfor %}
                    </tbody>

                </table>

            </div>
        </div>
    </div>
    {% include "meta/footer.html" %}
{% endblock %}
